import { List, Modal, Grid, DatePickerView, Toast } from 'antd-mobile';
import { Button, Divider, Alert } from 'antd';
import moment from 'moment';
import React, { useState } from 'react';
import { connect } from 'umi';
import { SwapRightOutlined } from '@ant-design/icons';
import BackIcon from '@/components/BackIcon';
import { useEffect } from 'react';
import { getFetch } from '@/utils/doFetch';
import { useMemo } from 'react';

const Item = List.Item;
// let Dopick = ({ value, onChange }) => {
//   return <PickerView
//     onChange={onChange}
//     //onScrollChange={this.onScrollChange}
//     value={value}
//     data={[
//       {
//         label: '春',
//         value: '春',
//       },
//       {
//         label: '夏',
//         value: '夏',
//       },
//     ]}
//     cascade={false}
//   />
// }

let Dodate = ({ value, onChange, limitDate }) => {
  let org = { [limitDate.key]: limitDate.date };
  return (
    <DatePickerView
      value={value}
      onChange={onChange}
      mode="date"
      {...org}
      //onValueChange={onValueChange}
    />
  );
};

let Invoice = ({ global: { userinfo, companies } }) => {
  let [state, setState] = useState({
      company_id: companies?.id,
      start:
        companies?.classify_name &&
        companies?.classify_name?.indexOf('一般纳税人') !== -1
          ? moment().startOf('month').format('YYYY-MM-DD')
          : moment().startOf('quarter').format('YYYY-MM-DD'),
      end:
        companies?.classify_name &&
        companies?.classify_name?.indexOf('一般纳税人') !== -1
          ? moment().endOf('month').format('YYYY-MM-DD')
          : moment().endOf('quarter').format('YYYY-MM-DD'),
    }),
    [vs, cvs] = useState(false),
    [iftype, ciftype] = useState({}),
    [data, setdata] = useState({}),
    [latest, setlatest] = useState({});

  //设置日期
  function setDate(key) {
    switch (key) {
      case 0:
        setState({
          ...state,
          start: moment().startOf('month').format('YYYY-MM-DD'),
          end: moment().endOf('month').format('YYYY-MM-DD'),
        });
        break;
      case 1:
        setState({
          ...state,
          start: moment().startOf('quarter').format('YYYY-MM-DD'),
          end: moment().endOf('quarter').format('YYYY-MM-DD'),
        });
        break;
      case 2:
        setState({
          ...state,
          start: moment().startOf('year').format('YYYY-MM-DD'),
          end: moment().endOf('year').format('YYYY-MM-DD'),
        });
        break;
      case 3:
        setState({
          ...state,
          start: moment()
            .add('month', -1)
            .startOf('month')
            .format('YYYY-MM-DD'),
          end: moment().add('month', -1).endOf('month').format('YYYY-MM-DD'),
        });
        break;
      case 4:
        setState({
          ...state,
          start: moment()
            .add('quarter', -1)
            .startOf('quarter')
            .format('YYYY-MM-DD'),
          end: moment()
            .add('quarter', -1)
            .endOf('quarter')
            .format('YYYY-MM-DD'),
        });
        break;
      case 5:
        setState({
          ...state,
          start: moment().add('year', -1).startOf('year').format('YYYY-MM-DD'),
          end: moment().add('year', -1).endOf('year').format('YYYY-MM-DD'),
        });
        break;
    }
    cvs(false);
  }

  useEffect(() => {
    let { start, end, company_id } = state;
    if (company_id) {
      getFetch({
        url: '/wbn-api/wechat/customers/company/invoice',
        params: { company_id, date_range_start: start, date_range_end: end },
      }).then((res) => {
        setdata(res.data);
      });

      getFetch({
        url: '/wbn-api/wechat/customers/company/invoice',
        params: {
          company_id,
          date_range_start: moment().add('year', -1).format('YYYY-MM-DD'),
          date_range_end: moment().format('YYYY-MM-DD'),
        },
      }).then((res) => {
        setlatest(res.data);
      });
    }
  }, [state.start, state.end, state.company_id]);

  let submoney = useMemo(() => {
    let {
      invoice_price_amount, //开票总金额
      input_tax_amount, //进项税总额
      titular_classify_tax_rate, //名义税率
      actual_classify_tax_rate, //实际税率
      classify_name, //公司类型
    } = data?.actual_classify_tax_rate
      ? data
      : {
          invoice_price_amount: 0,
          input_tax_amount: 0, //进项税总额
          titular_classify_tax_rate: null, //名义税率
          actual_classify_tax_rate: null, //实际税率
          classify_name: companies?.classify_name, //公司类型
        };
    actual_classify_tax_rate = actual_classify_tax_rate
      ? parseFloat(actual_classify_tax_rate)
      : 1;
    actual_classify_tax_rate = actual_classify_tax_rate / 100;

    titular_classify_tax_rate = titular_classify_tax_rate
      ? parseFloat(titular_classify_tax_rate)
      : 1;
    titular_classify_tax_rate = titular_classify_tax_rate / 100;

    invoice_price_amount = invoice_price_amount
      ? parseFloat(invoice_price_amount)
      : 0;
    input_tax_amount = input_tax_amount ? parseFloat(input_tax_amount) : 0;
    let kp = invoice_price_amount / (1 + titular_classify_tax_rate); //本月开票金额(不含税 )
    kp = kp.toFixed(1);

    let xx = kp * titular_classify_tax_rate; //销项税额
    xx = parseFloat(xx).toFixed(1);
    let zzs = kp * actual_classify_tax_rate; //本月应纳增值税额
    zzs = parseFloat(zzs).toFixed(1);
    let sqjx = xx - zzs - input_tax_amount; //尚缺进项税额
    sqjx = parseFloat(sqjx).toFixed(1);
    let sqjxpm =
      (sqjx / titular_classify_tax_rate) * (1 + titular_classify_tax_rate); //尚缺进项票面金额
    sqjxpm = parseFloat(sqjxpm).toFixed(1);

    let ycyjzzs = parseFloat(zzs) + parseFloat(sqjx); //预测应交增值税
    ycyjzzs = parseFloat(ycyjzzs).toFixed(1);

    let hkk =
      sqjx > 0
        ? 0
        : ((sqjx * -1) / titular_classify_tax_rate) *
          (1 + titular_classify_tax_rate); //还可开销售发票
    hkk = (
      parseFloat(hkk) *
      (1 +
        (actual_classify_tax_rate / titular_classify_tax_rate) *
          (1 + titular_classify_tax_rate))
    ).toFixed(1);

    let xgmzzs = 0;

    if (
      companies?.classify_name &&
      companies?.classify_name?.indexOf('一般纳税人') !== -1
    ) {
    } else {
      xgmzzs =
        invoice_price_amount -
        (data?.classify_remark ? parseFloat(data?.classify_remark) : 0) * 10000;
      if (xgmzzs > 0) {
        xgmzzs = invoice_price_amount * actual_classify_tax_rate;
      } else {
        xgmzzs = 0;
      }
    }

    return {
      kp,
      xx,
      zzs,
      sqjx,
      sqjxpm,
      ycyjzzs,
      hkk,
      xgmzzs,
    };
  }, [data]);

  return (
    <div style={{ width: '100%', height: '100%' }}>
      <BackIcon />
      <div style={{ height: 102, width: '100%' }}></div>
      <div
        style={{
          position: 'fixed',
          top: 0,
          width: '100%',
          backgroundColor: '#0ea9d6',
          zIndex: 99,
          paddingBottom: 12,
        }}
      >
        <div style={{ padding: 20 }} className="center">
          <span style={{ textAlign: 'center', color: '#fff' }}>开票时间段</span>
        </div>
        <div className="rows" style={{ padding: '0 12px' }}>
          <Button
            style={{ flex: 1 }}
            size="large"
            onClick={() => {
              cvs(true);
              ciftype({
                title: '开始时间',
                type: 'start',
              });
              setState({
                ...state,
                savedate: state.start,
              });
            }}
          >
            {state.start}
          </Button>
          <SwapRightOutlined style={{ padding: '0 12px' }}></SwapRightOutlined>
          <Button
            style={{ flex: 1 }}
            size="large"
            onClick={() => {
              cvs(true);
              ciftype({
                title: '结束时间',
                type: 'end',
              });
              setState({
                ...state,
                savedate: state.end,
              });
            }}
          >
            {state.end}
          </Button>
        </div>
      </div>

      <Divider style={{ margin: '12px 0 0 0' }}></Divider>
      <div className="rows" style={{ padding: 12 }}>
        <div
          style={{
            width: '100%',
            backgroundColor: 'rgba(0,0,0,0.05)',
          }}
        >
          <span>
            公司:<b>{companies?.name}</b> <br />
            开票类型:<b>{companies?.classify_name}</b>
          </span>
        </div>
      </div>
      <div className="rows" style={{ padding: '0px 12px 12px 12px' }}>
        <Button
          type="text"
          style={{
            flex: 1,
            backgroundColor: 'rgba(0,0,0,0.05)',
            display: 'flex',
          }}
        >
          名义税率 {data?.titular_classify_tax_rate || '-'}%
        </Button>
        <Divider type="vertical"></Divider>
        <Button
          type="text"
          style={{
            flex: 1,
            backgroundColor: 'rgba(0,0,0,0.05)',
            display: 'flex',
          }}
        >
          税负率 {data?.actual_classify_tax_rate}%
        </Button>
      </div>
      <div style={{ padding: '0px 12px 12px 12px' }}>
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: 12 }}
          message={`${state.start} 至 ${state.end} 开票信息`}
          description={
            companies?.classify_name &&
            companies?.classify_name?.indexOf('一般纳税人') !== -1 ? (
              <span style={{ color: '#666' }}>
                <b>吾帮你 友情提醒：</b>您好，贵公司已开发票
                {data?.invoice_price_amount || 0.0}元， 已开进项税额
                {data?.input_tax_amount || 0.0}元， 现在预测贵公司需要交增值税
                {submoney?.ycyjzzs > 0 ? submoney?.ycyjzzs : 0.0}元，
                按公司正常税负率测算应交
                {submoney?.zzs > 0 ? submoney?.zzs : 0.0}
                元， 尚缺{submoney?.sqjxpm > 0 ? submoney?.sqjxpm : 0.0}
                元进项票（含税）， 还可开销售发票（含税）{submoney?.hkk}元，
                如有疑问请联系我的客服（个人中心-我的客服）
              </span>
            ) : (
              <span>
                【吾帮你 友情提醒】您好，贵公司享受季度开票
                {data?.classify_remark}万元免征增值税的优惠政策， 贵公司已开票
                {data?.invoice_price_amount}元， 需交增值税{submoney?.xgmzzs}
                元， 贵公司最近12个月开票含税金额{latest?.invoice_price_amount}
                元
                （开票金额超过500万销售额，会被强制升级为一般纳税人，以后开票就只能开13个点票了）如有疑问请回复。
              </span>
            )
          }
        ></Alert>

        <List className="my-list">
          <Item extra={`${data?.invoice_price_amount}元`}>开票金额</Item>
          <Item extra={`${data?.invoice_num_amount}张`}>开票数量</Item>
          <Item extra={`${submoney?.kp}元`}>开票金额(不含税)</Item>
          <Item extra={`${submoney?.xx}元`}>销项税额</Item>
          {companies?.classify_name &&
            companies?.classify_name?.indexOf('一般纳税人') !== -1 && (
              <Item extra={`${submoney?.zzs}元`}>应纳增值税额</Item>
            )}

          <Item extra={`${data?.input_tax_amount}元`}>进项税额</Item>
          <Item extra={`${submoney?.sqjx > 0 ? submoney?.sqjx : 0}元`}>
            尚缺进项税额
          </Item>
          <Item extra={`${submoney?.sqjxpm > 0 ? submoney?.sqjxpm : 0}元`}>
            尚缺进项票面金额
          </Item>
          <Item extra={`${submoney?.ycyjzzs > 0 ? submoney?.ycyjzzs : 0}元`}>
            预测应交增值税
          </Item>
          {companies?.classify_name &&
            companies?.classify_name?.indexOf('一般纳税人') !== -1 && (
              <Item extra={`${submoney?.hkk}元`}>还可开销售发票13%(含税)</Item>
            )}
        </List>
      </div>

      <Modal
        popup
        visible={vs}
        onClose={() => {
          cvs(false);
        }}
        animationType="slide-up"
        afterClose={() => {}}
      >
        <div>
          <p
            style={{
              padding: 20,
              display: 'flex',
              justifyContent: 'space-between',
              marginBottom: 0,
            }}
          >
            <span>
              选择
              {iftype.title}
            </span>
            <a
              onClick={() => {
                setState({
                  ...state,
                  [iftype.type]: moment(state.savedate).format('YYYY-MM-DD'),
                });
                cvs(false);
                if (
                  !(
                    companies?.classify_name &&
                    companies?.classify_name?.indexOf('一般纳税人') !== -1
                  )
                ) {
                  Toast.info('小规模客户纳税额按季度结算,时间请选择季度');
                }
              }}
            >
              确定
            </a>
          </p>
          <Dodate
            value={moment(state.savedate).toDate()}
            onChange={(val) => {
              setState({
                ...state,
                savedate: moment(val).format('YYYY-MM-DD'),
              });
            }}
            limitDate={{
              date:
                iftype.type == 'start'
                  ? moment(state.end).toDate()
                  : moment(state.start).toDate(),
              key: iftype.type == 'start' ? 'maxDate' : 'minDate',
            }}
          ></Dodate>

          <Grid
            data={[
              {
                text: '本月',
              },
              {
                text: '本季度',
              },
              {
                text: '本年',
              },
              {
                text: '上月',
              },
              {
                text: '上季度',
              },
              {
                text: '去年',
              },
            ]}
            square={false}
            activeStyle={false}
            columnNum={3}
            itemStyle={{ marginTop: 0 }}
            onClick={(el, index) => {
              setDate(index);
            }}
          />
        </div>
      </Modal>
    </div>
  );
};
export default connect(({ global, loading }) => ({
  global,
  loading,
}))(Invoice);
